更改 Nginx 配置时,需要遵循正确的流程以确保服务不中断。
| 操作系统 | 主配置文件 |
|---|---|
| Linux | /etc/nginx/nginx.conf |
| macOS | /usr/local/etc/nginx/nginx.conf |
| Windows | conf/nginx.conf |
# Linux/macOS
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak.$(date +%Y%m%d%H%M%S)
# Windows
copy conf\nginx.conf conf\nginx.conf.bak
# Linux/macOS
sudo vim /etc/nginx/nginx.conf
# Windows
notepad conf\nginx.conf
# Linux/macOS
sudo nginx -t
# Windows
nginx -t
成功输出:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# Linux/macOS
sudo nginx -s reload
# Windows
nginx -s reload
# 检查进程
ps aux | grep nginx
# 测试服务
curl http://localhost
sudo nginx -s reload
# Linux
sudo systemctl restart nginx
# Windows
nginx -s stop
nginx
# 测试语法
sudo nginx -t
# 显示配置
sudo nginx -T
# 检查特定文件
sudo nginx -t -c /path/to/nginx.conf
# 错误:缺少分号
server {
listen 80
}
# 正确
server {
listen 80;
}
# 错误:括号不匹配
server {
listen 80;
# 错误:http 块中的指令放在 server 块中
server {
sendfile on;
}
# 错误:使用未定义的变量
proxy_pass http://$upstream;
http {
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
}
# 静态文件服务器
server {
listen 80;
server_name example.com;
# ...
}
server {
listen 80;
server_name $host;
root /var/www/$host;
}
# 测试配置
sudo nginx -t
# 显示配置
sudo nginx -T
# 1. 备份
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
# 2. 编辑
sudo vim /etc/nginx/nginx.conf
# 3. 测试
sudo nginx -t
# 4. 重新加载
sudo nginx -s reload
# 5. 验证
curl http://localhost
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
server {
listen 80;
server_name example.com;
root /var/www/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
# 查看详细错误
sudo nginx -t
# 检查语法
sudo nginx -T | grep -i error
# 检查进程
ps aux | grep nginx
# 检查日志
sudo tail -f /var/log/nginx/error.log
# 强制重启
sudo systemctl restart nginx
# 检查配置文件
sudo nginx -T
# 检查包含的文件
ls -la /etc/nginx/conf.d/
# 重新加载
sudo nginx -s reload